package cn.topevery.garden.dal.dao.impl;

import cn.topevery.garden.dal.dao.GreTreeRecordDao;
import cn.topevery.garden.entity.po.GreTree;
import cn.topevery.garden.entity.po.GreTreeRecord;
import cn.topevery.garden.entity.query.GreTreeRecordQuery;
import cn.topevery.garden.entity.vo.GreTreeRecordVO;
import cn.topevery.garden.framework.base.BaseDaoImpl;
import hw.topevery.basis.runtime.UserRuntime;
import hw.topevery.framework.db.CommandType;
import hw.topevery.framework.db.entity.DataPager;
import hw.topevery.framework.db.entity.SqlQueryMate;
import hw.topevery.framework.db.entity.SqlUpdateMate;
import hw.topevery.framework.db.enums.ScriptConditionEnum;
import hw.topevery.framework.entity.DbCsp;
import hw.topevery.framework.entity.KeyValue;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Repository;

import java.util.List;

/**
 * 行道树记录表
 *
 * @author code-generate
 * @date 2022-01-05
 */
@Repository
public class GreTreeRecordDaoImpl extends BaseDaoImpl<GreTreeRecord> implements GreTreeRecordDao {
    @Override
    public <P extends DbCsp> List<GreTreeRecord> getSearch(P para) {
        return null;
    }

    

    @Override
    public DataPager<GreTreeRecordVO> listPage(GreTreeRecordQuery query) {
        String table = "t_gre_tree_record tgtr";

        String columns = "tgtr.*";

        int pageIndex = query.pageIndex - 1;
        int pageSize = query.pageSize;

        SqlQueryMate sqlQueryMate = new SqlQueryMate(table).setColumns(columns).setOrderBy("tgtr.c_id desc");
        sqlQueryMate
                .where(true, "tgtr.c_db_status", ScriptConditionEnum.Eq, 0)
        ;

        return getDataPager(sqlQueryMate, pageSize, pageIndex, GreTreeRecordVO.class);
    }

    @Override
    public GreTreeRecord getEntityByColumn(String key,String value){
        KeyValue<String> map=new KeyValue<>();
        map.key=key;
        map.value=value;
        return getEntityByColumnEqValue(map);
    }

    @Override
    public Integer insert(GreTree greTree) {
        GreTreeRecord greTreeRecord = new GreTreeRecord();
        //将旧的记录修改为历史版本
        SqlUpdateMate sqlUpdateMate = new SqlUpdateMate("t_gre_tree_record");
        sqlUpdateMate.setColumnValue(true, "c_is_new", 0)
                .where(true, "c_tree_int_id", ScriptConditionEnum.Eq, greTree.getId());
        run(sqlUpdateMate.getSql(), CommandType.Text, dbCommand -> {
            sqlUpdateMate.getParameters().forEach(dbCommand::addParameter);
            dbCommand.executeNonQuery();
        });
        BeanUtils.copyProperties(greTree, greTreeRecord, "id");
        greTreeRecord.setTreeIntId(greTree.getId());
        greTreeRecord.setIsNew(1);
        //存入新的记录
        insert(UserRuntime.getSysUser().userId, greTreeRecord);
        return  greTreeRecord.getId();
    }
}
